import {getWxUserInfo, testLogin} from '@/api/common/index.js'
import pagesJson from '@/pages.json'
import {getWxCode, getUrlCode, isWechat, replaceWxUrl} from '@/script/wx-premission.js'
import wechat from '@/script/wechat.js'
import wxSDK from 'jweixin-module'
import {mapActions} from 'vuex'
export default {
	data(){
		return {}
	},
	methods: {
		...mapActions(['setNeedRegister']),
		showWxApp(){
			return new Promise((reslove, reject) => {
				if(this.needWxLogin() === true && isWechat() === true){
					this.wxLogin().then(boo => {
						console.log(boo, 7777)
						reslove(boo)
					})
				}else{
					reslove(false)
				}
			})
			
		},
		needWxLogin(){
			let {subPackages} = pagesJson, routeList = []
			subPackages.forEach(pa => {
				routeList = [...routeList, ...pa.pages]
			})
			let idx = routeList.findIndex(i => (`/${i.root}/${i.path}` == location.pathname))
			if(idx == -1) return
			let page = routeList[idx]
			let {login = false} = page.style
			return login
		},
		wxLogin(){
			return new Promise(async (resolve, reject) => {
				let _self = this
				const token = uni.getStorageSync('ICarddWx') || ''
				if(token) return resolve(true)
				let code = getUrlCode('code')
				if(!code){
					getWxCode(location.href)
				}else{
					let isSuccess = await _self.getWxUserInfo(code, location).catch((err) => {
						let data = err.data
						if(data.code == 501){
							replaceWxUrl()
							getWxCode(location.href)
						}
					})
					resolve(isSuccess)
				}
			})
		},
		getWxUserInfo(code, location) {
			let _self = this
			return new Promise((resolve, reject) => {
				getWxUserInfo({code}).then(res => {
					let {isRegister = false, token} = res.data	
					if(isRegister){
						let {name} = _self.$$router.getRoute(_self), location = {}
						let {query } = _self.$route
						if(name == 'hdHome'){
							uni.setStorage({
								key: `icar-wxActive`,
								data: {a: (query || {}).a, i: (query || {}).i}
							})
						}
						uni.setStorage({
							key: `icar-wxuser`,
							data: {...res.data, ...location},
							success: () => {
								_self.setNeedRegister(true).then(() => {
									resolve(false)
								})
								// _self.$$router.replace({name: 'registerTel', query:{
								// 	redirect: name
								// }})
							}
						})
					}else{
						_self.setNeedRegister(false).then(() => {
							uni.setStorage({
								key: `ICarddWx`,
								data: token,
							})
							resolve(true)
						})
					}
				}).finally(() => {
					replaceWxUrl()
				})
			})
		}
	},
}